package com.example.demo.controller;

import com.example.demo.dto.QuestionDTO;
import com.example.demo.mapper.QuestionMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import com.example.demo.service.QuestionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author redjava
 * @create 2021-07-23 15:27
 */
@Controller
public class ProfileController {
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuestionService questionService;
    @GetMapping("/profile/{action}")
    public String profile(@PathVariable(name = "action") String action,
                          HttpServletRequest request,
                          Model model) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        if ("questions".equals(action)) {
            model.addAttribute("section", "questions");
            model.addAttribute("sectionName","我的提问");
        }else if("reply".equals(action)){
            model.addAttribute("section","reply");
            model.addAttribute("sectionName","最新回复");
        }
        return "profile";
    }
    @PostMapping("/profile/getQuestions")
    @ResponseBody
    public PageInfo<QuestionDTO> getQuestions(@RequestParam(name = "page", defaultValue = "1") Integer page){
        //查询总记录数
        int questionsCount = questionMapper.countbyId(1);
        int totalPages = 0;
        if (questionsCount % 5 == 0) {
            totalPages = questionsCount / 5;
        } else {
            totalPages = questionsCount / 5 + 1;
        }
        PageHelper.startPage(page,5);
        List<QuestionDTO> questionDTOS = questionService.listById(1);
        PageInfo<QuestionDTO> pageInfo = new PageInfo<>(questionDTOS);
        pageInfo.setPages(totalPages);
        return pageInfo;

    }
}
